import React, { Component } from 'react'
import { authContext } from './authContext'
import { withRouter, Prompt } from 'react-router-dom'

@withRouter
export default class AuthButton extends Component {
  constructor(props) {
    super(props)
    const { history } = this.props
    history.listen((location) => {
      // if (location.pathname === '/login' && location.state.from.pathname === '/protected') {
      //   if(window.confirm('你真的要离开吗？')) {
      //     // history.push('/')
      //   } else {
      //     history.push('/protected')
      //   }
      // }
    })
  }

  static contextType = authContext

  state = {
    isSignout: false
  }

  handleClick = (signout, history) => {
    return () => {
      this.setState({
        isSignout: true
      })
      signout(() => history.push("/"));
    }
  }

  render() {
    const { user, signout } = this.context
    const { history } = this.props

    return (
      <>
        {
          user ? (
            <p>
              Welcome!{" "}
              <button
                onClick={this.handleClick(signout, history)}
              >
                Sign out
              </button>
            </p>
          ) : (
            <p>You are not logged in.</p>
          )
        }
        {/* <Prompt
          message={(location, action) => {
            console.log(location.pathname)
            if (action === 'POP') {
              // console.log("Backing up...")
            }

            // return true
        
            return location.pathname.startsWith("/login")
              ? `Are you sure you want to go to ${location.pathname}?`
              : true
          }}
        /> */}
      </>
    )
  }
}
